package view;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.servlet.view.AbstractView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Map;

/**
 * @author 徒有琴
 */
public class JsonView extends AbstractView {
    public JsonView() {
    }

    private Map res;

    public JsonView(Map res) {
        this.res = res;
    }

    @Override
    public String getContentType() {
        return "application/json; charset=UTF-8";
    }

    @Override
    protected void renderMergedOutputModel(Map map, HttpServletRequest httpServletRequest, HttpServletResponse response) throws Exception {
        System.out.println(map);
        ObjectMapper mapper = new ObjectMapper();
        //设置Date类型的格式，默认是显示毫秒数
        mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        //需要注意的是放入model的对象一定要实现Serializable接口才能转化成json
        String jsonStr = mapper.writeValueAsString(map.get("result"));
        response.setContentType(getContentType());
        response.setHeader("Cache-Control", "no-cache");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.print(jsonStr);
            out.flush();
        } catch (IOException e) {
        } finally {
            if (out != null) {
                out.close();
                out = null;
            }
        }

    }
}
